﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.AutoOrder_Fuji.IView;
using System.Threading;
using MINERP.MODEL.AutoOrder_Fuji;
using MINERP.BLL.AutoOrder;
using MINERP.BLL.Common;
using MINERP.COM;

namespace MINERP.AutoOrder_Fuji.Presenter
{
    public class MainvPresenter
    {
        private IMainView _view;
        private RemoteMonitorFolderBLL_Fuji _remoteMoniBLL;
        private DownLoadOrderFile_Fuji _downLoadBLL;
        private List<AutoOrderFolder_Info> _listFolder;
        private const int MAXFOLDERNUM = 100;//最多只保留100个文件包的记录

        public MainvPresenter(IMainView view)
        {
            _view = view;
            _listFolder = new List<AutoOrderFolder_Info>();
            _remoteMoniBLL = new RemoteMonitorFolderBLL_Fuji();
            _downLoadBLL = new DownLoadOrderFile_Fuji();

            IniFrm();
        }

        /// <summary>
        /// 初始化界面，主要是定时监控热文件夹
        /// </summary>
        private void IniFrm()
        {
            try
            {
                StartAutoWork();
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }

        #region help methods
        private Thread _autoWorkThread;
        private bool _isStop = false;

        /// <summary>
        /// 开始自动监控并解析
        /// </summary>
        public void StartAutoWork()
        {
            try
            {
                _isStop = false;

                if (_autoWorkThread == null)
                {
                    _autoWorkThread = new Thread(AutotWork);
                    _autoWorkThread.IsBackground = true;
                    _autoWorkThread.Start();
                }
                else if (_autoWorkThread.ThreadState == ThreadState.Stopped || _autoWorkThread.ThreadState == ThreadState.Background || _autoWorkThread.ThreadState == ThreadState.WaitSleepJoin || _autoWorkThread.ThreadState == ThreadState.Suspended)
                {
                    _autoWorkThread = new Thread(AutotWork);
                    _autoWorkThread.IsBackground = true;
                    _autoWorkThread.Start();
                }
                else
                {
                    //MessageBox.Show("无法执行操作，请重试！");
                    //_view.CloseFrm();
                }

                //AutotWork();//修改报表时不能用多线程
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 关闭
        /// </summary>
        public void StopAutoWork()
        {
            try
            {
                _isStop = true;
                //_view.SetBtn("正在停止拼板", false);
            }
            catch (ThreadAbortException ex)
            {
                Thread.ResetAbort();
            }
            finally
            {
                //停止成功
            }
        }

        private void AutotWork()
        {
            while (!_isStop)
            {
                if (_listFolder == null || _listFolder.Count(f => f.Status == AutoOrderStatus.WaitDownLoad) < 1)
                {
                    try
                    {
                        GetAllOrder();
                    }
                    catch (Exception ex)
                    {
                        WriteLogForCheck.WriteLogFile(DateTime.Now + ex.Message + ex.Source + ex.TargetSite.ToString());
                    }

                }

                try
                {
                    DownLoadAndResolveOneFoler();
                }
                catch (Exception ex)
                {

                    WriteLogForCheck.WriteLogFile(DateTime.Now + ex.Message + ex.Source + ex.TargetSite.ToString());
                    _isStop = true;
                    System.Windows.Forms.MessageBox.Show("请排除错误后,关闭解析服务,再重新启动" + ex.Message);
                    break;
                }

                Thread.Sleep(2000);//2秒去刷新一次
            }
        }

        /// <summary>
        /// 得到远程开单目录下的所有文件列表
        /// </summary>
        void GetAllOrder()
        {
            List<AutoOrderFolder_Info> tmpList;
            try
            {
                tmpList = _remoteMoniBLL.GetAllFolderList();
            }
            catch (Exception ex)
            {

                StopAutoWork();
                System.Windows.Forms.MessageBox.Show("在获取远程开单列表时出错：" + ex.Message);
                return;
            }

            foreach (var fi in tmpList)
            {
                if (_listFolder.Find(f => f.OrderXMLpath == fi.OrderXMLpath) == null)
                {
                    if (_listFolder.Count >= MAXFOLDERNUM)
                    {
                        _listFolder.Remove(_listFolder.OrderBy(f => f.CreateTime).FirstOrDefault(f => f.Status == AutoOrderStatus.Successed));
                    }
                    _listFolder.Add(fi);
                }
            }

            //_view.BindStatusCmbList(_listFolder.Select(f => f.Status).ToList());

            ShowGridView();
        }
        //记录当前界面上查看状态
        private AutoOrderStatus _curSelectStatus;


        public void ShowGridView()
        {
            ShowGridView(_curSelectStatus);
        }
        /// <summary>
        /// 根据选定的状态进行显示相应的内容
        /// </summary>
        /// <param name="selectStatus"></param>
        public void ShowGridView(AutoOrderStatus selectStatus)
        {
            if (selectStatus == AutoOrderStatus.WaitDownLoad)//查看等待下载和正在下载正在解包的
            {
                _view.DisPlayFolder(_listFolder.Where(f => f.Status != AutoOrderStatus.Error && f.Status != AutoOrderStatus.Successed).ToList());
            }
            else
            {
                _view.DisPlayFolder(_listFolder.Where(f => f.Status == selectStatus).ToList());
            }
            _curSelectStatus = selectStatus;
        }

        /// <summary>
        /// 得到一个按时间排序最早的下载和解析一个文件夹
        /// </summary>
        /// <param name="oneToMoveOrderFolder"></param>
        void DownLoadAndResolveOneFoler()
        {
            string msg = string.Empty;//获取相关的错误信息
            string strDisFolder = string.Empty;//移动的目标文件夹路径，即等待开单下面的路径

            AutoOrderFolder_Info oneToMoveOrderFolder = _listFolder.OrderBy(f => f.CreateTime).FirstOrDefault(f => f.Status == AutoOrderStatus.WaitDownLoad);
            if (oneToMoveOrderFolder != null)
            {
                oneToMoveOrderFolder.Status = AutoOrderStatus.DownLoading;//取列表中最先创建的第一个文件夹进行移动操作

                _view.refreshDataGrid();

                if (_downLoadBLL.DownloadFolderFromRemoteFolder(oneToMoveOrderFolder, out msg, out strDisFolder) == 0)
                {
                    RemoteMonitorFolderBLL_Fuji remotebll = new RemoteMonitorFolderBLL_Fuji();
                    ReadFujiXML readXml = new ReadFujiXML(remotebll.GetOneFromSomeFolder(strDisFolder).OrderXMLpath);
                    oneToMoveOrderFolder.Status = AutoOrderStatus.Resolving;
                    _view.refreshDataGrid();
                    if (!readXml.ResolveOrderXML(out msg))
                    {
                        oneToMoveOrderFolder.Status = AutoOrderStatus.Error;
                        oneToMoveOrderFolder.Remark = msg;
                        _view.refreshDataGrid();
                    }
                    else//成功后则删除掉下载和等待开单文件夹以及里面的内容
                    {
                        oneToMoveOrderFolder.Status = AutoOrderStatus.Successed;
                        _view.refreshDataGrid();

                        FileBLL.DeleteDirectory(oneToMoveOrderFolder.FolderPath);
                        FileBLL.DeleteDirectory(strDisFolder);
                    }
                }
                else //如果出错了，需要将
                {
                    oneToMoveOrderFolder.Status = AutoOrderStatus.Error;
                    oneToMoveOrderFolder.Remark = msg;
                    _view.refreshDataGrid();
                }
            }
        }

        #endregion


        /// <summary>
        /// 将错误的列表恢复到正常的状态
        /// </summary>
        /// <param name="selectedOrder"></param>
        internal void ResumeErr(List<AutoOrderFolder_Info> selectedOrder)
        {
            foreach (var o in selectedOrder)
            {
                o.Status = AutoOrderStatus.WaitDownLoad;
                o.Remark = string.Empty;
            }

            ShowGridView();
        }

        /// <summary>
        /// 清空缓存中的List
        /// </summary>
        internal void ClearListAndRefresh()
        {
            if (_listFolder != null || _listFolder.Count > 0)
            {
                _listFolder = _listFolder.Where(o => o.Status != AutoOrderStatus.Successed).ToList();
                ShowGridView();
            }
        }

        /// <summary>
        /// 打开监控文件夹
        /// </summary>
        internal void OpenMonitorFolder()
        {
            _remoteMoniBLL.OpenRemoteMonitorFolder();
        }
    }
}
